﻿using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.PrintService;
using CoreShop.Services;
using Loading;
using NPOI.Util;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;
using static CoreShop.Library.GlobalEnumVars;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace CoreShop.App
{
    public partial class frmFoodLablePrin : UIForm
    {
        private List<corecmsfoodordering> orderingDetail = null;
        private corecmsfoodorderingmaster orderingMaster = null;
        OpaqueCommand cmd1 = new OpaqueCommand();
        public frmFoodLablePrin()
        {
            InitializeComponent();
            dgvGoodsList.BackgroundColor = Color.White;
            dgvGoodsList.CellFormatting += DataGridView1_CellFormatting;
        }

        // 事件处理方法
        private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // 检查是否是有效单元格
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                DataGridView dgv = sender as DataGridView;
                DataGridViewCell cell = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex];

                // 跳过新行
                if (dgv.Rows[e.RowIndex].IsNewRow) return;

                // 示例1：根据列索引设置不同列的颜色
                if (e.ColumnIndex < 7)
                {
                    cell.Style.BackColor = Color.AliceBlue;
                }               
            }
        }

        private void frmfoodtask_Load(object sender, System.EventArgs e)
        {
            int deskId = (int)GlobalEnumVars.OrderDeskType.OrderingLabel;
            var masterSrv = new corecmsfoodorderingmasterServices();
            orderingMaster = masterSrv.QueryByDeskId(deskId, 0);//开台模式
            if (orderingMaster == null)
                orderingMaster = masterSrv.GreateOrderingMaster(AppConstVars.sysUser, deskId, AppConstVars.sysUser.id, 0, "", 0);
            GetOrderingDetail();
            BindBillPrintData();
        }

        private void BindBillPrintData()
        {
            List<corecmsprintbilltemplate> templateList = new corecmsprintbilltemplateServices().AsQueryable()
                .Where(p => p.billtypeId == (int)GlobalEnumVars.PrintbillType.Label).ToList();
            this.cmbBillLabel.Items.Clear();
            cmbBillLabel.DataSource = templateList;
            cmbBillLabel.DisplayMember = "name";
            cmbBillLabel.ValueMember = "id";
            int sBarcodeTemplateId = CommFunc.ConvertToInt32(IniFiles.ReadIniData("Local", "BarcodeTemplateId"));
            if (sBarcodeTemplateId > 0) 
                this.cmbBillLabel.SelectedValue = sBarcodeTemplateId;
        }

        private void GetOrderingDetail()
        {
            orderingDetail = new corecmsfoodorderingServices().GetListByOrderId(orderingMaster.orderId);
            dgvGoodsList.AutoGenerateColumns = false;
            this.binDetail.DataSource = orderingDetail;
            this.dgvGoodsList.DataSource = this.binDetail;
        }
                
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnClearData_Click(object sender, EventArgs e)
        {
            if (!ShowAskDialog("提示：", "确定要删除所有待打印数据吗？", UIStyle.Red)) return;
            new corecmsfoodorderingServices().Delete(p => p.orderId == orderingMaster.orderId);
            GetOrderingDetail();
            ShowInfoTip("删除完成。");
        }

        private void SaveTemplateId()
        {
            try
            {
                IniFiles.IniWriteValue("Local", "BarcodeTemplateId", cmbBillLabel.SelectedValue.ObjToInt().ToString());
            }
            catch { }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            var sTemplateId = cmbBillLabel.SelectedValue.ObjToInt();
            var billtemplate = new corecmsprintbilltemplateServices().GetById(sTemplateId);
            if (billtemplate == null) 
            {
                UIMessageBox.Show("没有选择打印模板");
                return;
            }
            SaveTemplateId();
            new ReportServices().SetPrintCodebar(orderingMaster, billtemplate, isPrintPreview.Checked);
        }

        private async void AddDataRows(List<corecmsfoodspec> foodspecList)
        {
            cmd1.ShowOpaqueLayer(pnl_Form, 125, true);
            try
            {
                var foodorderingSrv = new corecmsfoodorderingServices();
                foreach (var foodspec in foodspecList)
                {
                    var ordering = foodorderingSrv.CreateByFoodId(foodspec.id, 1, 0);
                    ordering.orderId = orderingMaster.orderId;
                    ordering.setPrice = foodspec.vipPrice;//setPrice存放会员价
                    ordering.taskTitle = foodspec.place;//taskTitle存放地产                    
                    await foodorderingSrv.InsertOrUpdateAsync(ordering);
                }
                GetOrderingDetail();
            }
            catch (Exception)
            {
            }
            finally { cmd1.HideOpaqueLayer(); }

        }

        private void btnSelectGoods_Click(object sender, EventArgs e)
        {
            var frm = new frmFoodSelect(null, true);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                AddDataRows(frm.specList);
            }
            frm.Dispose(); 
        }

        private void btnSaveGoods_Click(object sender, EventArgs e)
        {
            SaveTemplateId();
            new corecmsfoodorderingServices().InsertOrUpdateAsync(orderingDetail);
            ShowInfoTip("保存完成。");
        }
    }
}
